<template>
  <Dialog v-model="visible" width="30vw" title="选择上级编码">
    <div>当前编码：{{ modelValue }}, 已选择编码：{{ currentCode }}<ElButton type="primary" link @click="currentCode = ''">删除</ElButton></div>
    <el-tree :data="data" @node-click="onNodeClick" />
    <template #footer>
      <div class="flex justify-center items-center">
        <el-button type="primary" @click="ok">确定</el-button>
        <el-button @click="hide">关闭</el-button>
      </div>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
  import { Dialog } from '@/components/Popup';
  import { ElTree, ElButton } from 'element-plus';
  import { onMounted, ref } from 'vue';
  import request from "@/utils/request"

  const props = defineProps<{modelValue: string, treeActionUrl: string, codeColumnName?: string}>()
  const emits = defineEmits(['update:modelValue'])
  
  const visible = ref(false)
  const currentCode = ref(props.modelValue)
  const codeColumnName = props.codeColumnName || 'code'

  const data = ref()
  const init = (nodes) => {
    for(const i in nodes) {
      const node = nodes[i]
      node.value = node[codeColumnName]
      node.label = node.name
      const children = node.children
      if(children) init(children)
    }
  }

  const onNodeClick = (data) => currentCode.value = data[codeColumnName]
  const ok = () => {
    emits('update:modelValue', currentCode.value)
    hide()
  }

  onMounted(async () => {
    const res = await request.get(props.treeActionUrl)
    data.value = res.data
    init(data.value)
  })

  const show = () => visible.value = true
  const hide = () => visible.value = false
  defineExpose({ show, hide })
</script>